package com.devicemantra.coordinate.dataobjects;

import java.util.Iterator;
import java.util.List;

import javax.jdo.JDOException;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import com.devicemantra.coordinate.ds.tests.PMF;
import com.devicemantra.coordinate.exceptions.dataobjects.CDatabaseException;
import com.devicemantra.coordinate.exceptions.operations.CStateAlreadyExistsException;
import com.devicemantra.coordinate.exceptions.operations.CStateDoesNotExistsException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/** TODO - Most of the *Factory classes are written very badly 
 * put some thought into optimizing for performance */

public class CStateFactory 
{
	
		public static boolean checkStateExists(String pStateName) 
		{
			boolean lDoesExist = true;
			Key lNewStateKey = KeyFactory.createKey(CState.class.getSimpleName(), pStateName);
			PersistenceManager pm = PMF.get().getPersistenceManager();
			try
			{
				if(null != pm )
					pm.getObjectById(CState.class,lNewStateKey);
				else
					System.out.println("Error: could not create PMF");
				
			} catch(JDOObjectNotFoundException e)
			{
				lDoesExist = false;
			}catch(JDOException e) {
				e.printStackTrace();
			}
			
			return lDoesExist;
		}
		
		public static Key createKey(String pStateName)
		{
			Key lNewStateKey = KeyFactory.createKey(CState.class.getSimpleName(), pStateName);
			return lNewStateKey;
		}
		
		public static CState getState(String pStateName)
		{
			CState lDept = null;
			PersistenceManager pm = PMF.get().getPersistenceManager();
			if( checkStateExists(pStateName))
			{
				Key lStateKey = createKey(pStateName);
				try
				{
					lDept = pm.getObjectById(CState.class,lStateKey);
				} catch(JDOObjectNotFoundException e)
				{
					System.out.println("[COORDINATE] ERROR: Some problem retreiving object");
					e.printStackTrace();
				}
			}
			
			return lDept;
		}
		
		public static List<CState> getAllStates()
		{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			javax.jdo.Query query = pm.newQuery(CState.class);
			/*query.setFilter("mStateName == lDeptName");
			query.declareParameters("String lDeptName");*/
		    List<CState> lListStates = (List<CState>) query.execute(/*"FINANCE" */);
		    Iterator<CState> lListStatesIter = lListStates.iterator();
		    while (lListStatesIter.hasNext())
		    {
	               CState lState = lListStatesIter.next();
				//	System.out.println("State NAME - " + lState.getName());
	        }
			return lListStates;
		}
	
		public static void createNewState(String pNewStateName) throws CStateAlreadyExistsException, CDatabaseException 
		{
			/* First check whether such a State exists using Keys */
			boolean lDoesStateExist = checkStateExists(pNewStateName);
			if(false == lDoesStateExist)
			{
				CState lState = new CState(pNewStateName);
				Key lNewStateKey = createKey(pNewStateName);
				System.out.println("State Key is " + KeyFactory.keyToString((lNewStateKey)));
				lState.setStateId(lNewStateKey);
				try
				{
					PersistenceManager pm = PMF.get().getPersistenceManager();
					pm.makePersistent(lState);
					pm.close();
				} catch(JDOException e) {
					throw new CDatabaseException(e.getMessage());
				}
			}
			else
			{
				/* State with that name already exists */
				throw new CStateAlreadyExistsException("State with the name " + pNewStateName + " already exists");
				
			}
		}
		
		public static void deleteState(String pStateName) throws CDatabaseException, CStateDoesNotExistsException 
		{
			boolean lDoesExist = false;
			CState lState = null;
			Key lNewStateKey = KeyFactory.createKey(CState.class.getSimpleName(), pStateName);
			PersistenceManager pm = PMF.get().getPersistenceManager();
			try
			{
				if(null != pm ) {
					lState = pm.getObjectById(CState.class,lNewStateKey);
					lDoesExist = true;
				}
				else
					throw new CDatabaseException("ERROR: Could not create PMF");
			}catch(JDOObjectNotFoundException e)
			{
				lDoesExist = false;
				throw new CStateDoesNotExistsException("ERROR: State with the name " + pStateName + " does not exist");
			}catch(JDOException e) {
				e.printStackTrace();
				lDoesExist = false;
				throw new CDatabaseException("ERROR: Database error");
			}
			
			if(true == lDoesExist)
			{
				if(lState != null)
				{
					try
					{
						pm.deletePersistent(lState);
						pm.close();
					} catch(JDOException e) {
						throw new CDatabaseException(e.getMessage());
					}
				}
				
			}
		}
		
}
